package cn.tedu.jsd2209.csmall.product.ex.handler;

import cn.tedu.jsd2209.csmall.product.ex.ServiceException;
import cn.tedu.jsd2209.csmall.product.web.JsonResult;
import cn.tedu.jsd2209.csmall.product.web.ServiceCode;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult handlerServiceException(ServiceException e){
        return JsonResult.fail(e);
    }

    @ExceptionHandler
    public JsonResult handlerConstraintViolationException(ConstraintViolationException e){
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        StringJoiner stringJoiner = new StringJoiner(",");
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
             stringJoiner.add(constraintViolation.getMessage());

        }
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,stringJoiner.toString());
    }

    @ExceptionHandler
    public JsonResult handlerBindException(BindException e){
       // String message = e.getFieldError().getDefaultMessage();
//        StringJoiner stringJoiner = new StringJoiner(",");
//        List<ObjectError> allErrors = e.getAllErrors();
//        for (ObjectError allError : allErrors) {
//            String defaultMessage = allError.getDefaultMessage();
//            stringJoiner.add(defaultMessage);
//        }
//        String message = stringJoiner.toString();

         //   String prefix = "添加相册失败";
           // String suffix ="!";
        String message = e.getFieldError().getDefaultMessage();

        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);
    }
}
